package janino;

import org.codehaus.commons.compiler.CompilerFactoryFactory;
import org.codehaus.commons.compiler.IExpressionEvaluator;
import org.springframework.util.StopWatch;

/**
 * Sample application which demonstrates how to use the {@link IExpressionEvaluator} class.
 */
public class ShippingCost {

    public static void main(String[] args) throws Exception {
        //StopWatch 计算方法耗时的优雅方式，这里使用的是spring的，guava和apach-commons都有类似的功能
        StopWatch sw = new StopWatch();

        // Convert command line argument to call argument "total".
        Object[] arguments = {new Double(120), new Integer(10)};

        sw.start("实例化表达式解析器");
        // Create "ExpressionEvaluator" object.
        IExpressionEvaluator ee = CompilerFactoryFactory.getDefaultCompilerFactory().newExpressionEvaluator();
        sw.stop();
        ee.setExpressionType(boolean.class);
        ee.setParameters(new String[]{"total", "count"}, new Class[]{double.class, int.class});
        sw.start("设置表达式");
        ee.cook("count == 10 || total >= 100.0 && count > 8");
        sw.stop();

        sw.start("计算表达式");
        // Evaluate expression with actual parameter values.
        Object res = ee.evaluate(arguments);
        sw.stop();

        // Print expression result.
        System.out.println("Result = " + res);

        System.out.println(sw.prettyPrint());
        System.out.println(sw.shortSummary());
    }
}